﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using IMClient.Model.UI;
using System.Windows;

namespace IMClient.ViewModels
{
    public partial class FriendDetailsViewModel : ObservableObject
    {
        [ObservableProperty]
        private string name = string.Empty;

        [ObservableProperty]
        private string avatar = string.Empty;

        [ObservableProperty]
        private string friendId = string.Empty;

        public FriendDetailsViewModel(FriendViewModel friend)
        {
            Name = friend.Name;
            Avatar = friend.Avatar;
            FriendId = friend.Id;
        }

        [RelayCommand]
        private void SendMessage()
        {
            // 获取 ChatPage 的单例 ViewModel
            var chatViewModel = ChatWindowViewModel.Instance.GetChatPageViewModel();

            if (chatViewModel == null) 
                return;
            
            // 查找是否已存在该好友的聊天项
            var existingFriend = chatViewModel.ChatParticipants
                .FirstOrDefault(f => f.Id == FriendId);

            if (existingFriend == null)
            {
                // 如果不存在，创建新的聊天项
                var newFriend = new FriendViewModel
                {
                    Id = FriendId,
                    Name = Name,
                    Avatar = Avatar,
                    LastMessage = string.Empty,
                    LastMessageTime = string.Empty,
                    UnreadCount = 0
                };
                chatViewModel.ChatParticipants.Add(newFriend);
                chatViewModel.FilterParticipants(string.Empty);
                chatViewModel.SelectedParticipant = newFriend;
            }
            else
            {
                // 如果存在，直接选中
                chatViewModel.SelectedParticipant = existingFriend;
            }

            // 导航到聊天页面 
            ChatWindowViewModel.Instance.NavigateToChat();
        }

        [RelayCommand]
        private void DeleteFriend()
        {
            var result = MessageBox.Show(
                $"确定要删除好友 {Name} 吗？", 
                "删除好友", 
                MessageBoxButton.YesNo, 
                MessageBoxImage.Question);

            if (result == MessageBoxResult.Yes)
            {
                // TODO: 实现删除好友的逻辑
                MessageBox.Show("删除好友功能待实现");
            }
        }
    }
}
